package com.eight.common.utils.enumeration;

import org.apache.commons.lang3.ObjectUtils;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class EnumFinder<K, T extends Enum<T>> {
    private static Map<Class<? extends Enumerable<?>>, Map<? extends Object, ? extends Enumerable<?>>> valEnumMap = new ConcurrentHashMap();
    protected Map<K, T> map = new HashMap();

    public EnumFinder() {
        Class<?> enumCls = com.eight.common.utils.enumeration.GenericUtils.instance().getGenericCls(this, 2, EnumFinder.class);
        this.init(enumCls);
    }

    public EnumFinder(Class<T> enumCls) {
        this.init(enumCls);
    }

    private void init(Class enumCls) {
        if (!valEnumMap.containsKey(enumCls)) {
            valEnumMap.put((Class<? extends Enumerable<?>>) enumCls, new HashMap());
        }

        Map<Object, T> eMap = (Map)valEnumMap.get(enumCls);
        if (eMap.isEmpty()) {
            EnumSet.allOf(enumCls).stream().forEach((e) -> {
                eMap.put(this.getKey((T) e), (T) e);
            });
        }

    }

    public T get(K key) {
        return this.get(key, null);
    }

    public T get(K key, T defaultValue) {
        Class thisCls;
        for(thisCls = this.getClass(); thisCls.isAnonymousClass(); thisCls = thisCls.getEnclosingClass()) {
        }

        return (T) ObjectUtils.defaultIfNull((Enum)((Map)valEnumMap.get(thisCls)).get(key), defaultValue);
    }

    public abstract K getKey(T var1);

    public static <E extends Enum<E>, K> E findByValue(Class<E> enumCls, K value) {
        if (value == null) {
            return null;
        } else {
            if (!valEnumMap.containsKey(enumCls)) {
                EnumFinder var10001 = new EnumFinder<K, E>(enumCls) {
                    @Override
                    public K getKey(E enumObj) {
                        return (K) ((Enumerable)enumObj).value();
                    }
                };
            }

            return !valEnumMap.containsKey(enumCls) ? null : (E) ((Map)valEnumMap.get(enumCls)).get(value);
        }
    }
}
